import { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, useNavigate } from 'react-router-dom';
import './App.css';
import MarkdownEditor from './pages/MarkdownEditor';
import KnowledgeBrowser from './pages/KnowledgeBrowser';
import ArticleDetail from './pages/ArticleDetail';

const menuData = {};

const CategoryService = {
  async fetchCategories() {
    try {
      const response = await fetch('http://localhost:8101/api/knowledge/category/one/list/all', {
        method: 'GET',
        mode: 'cors',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      if (result.code === 200) {
        return result.data;
      }
      console.error('Failed to fetch categories:', result.message);
      return [];
    } catch (error) {
      console.error('Error fetching categories:', error);
      return [];
    }
  },
  
  async fetchSubCategories(parentId) {
    try {
      const response = await fetch(`http://localhost:8101/api/knowledge/category/two/list/parent/${parentId}`, {
        method: 'GET',
        mode: 'cors',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      if (result.code === 200) {
        return result.data;
      }
      console.error('Failed to fetch subcategories:', result.message);
      return [];
    } catch (error) {
      console.error('Error fetching subcategories:', error);
      return [];
    }
  },
  
  async fetchArticles(categoryOneId, categoryTwoId, pageNum = 1, pageSize = 10) {
    try {
      const params = new URLSearchParams({
        categoryOneId,
        categoryTwoId,
        status: 1, // 只查询已发布的文章
        pageNum,
        pageSize
      });
      
      const response = await fetch(`http://localhost:8101/api/knowledge/article/list?${params}`, {
        method: 'GET',
        mode: 'cors',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      if (result.code === 200) {
        return result.data;
      }
      console.error('Failed to fetch articles:', result.message);
      return { list: [], total: 0, pageNum: 1, pageSize, totalPage: 0 };
    } catch (error) {
      console.error('Error fetching articles:', error);
      return { list: [], total: 0, pageNum: 1, pageSize, totalPage: 0 };
    }
  }
};

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/new" element={<MarkdownEditor />} />
        <Route path="/" element={<HomePage />} />
        <Route path="/knowledge" element={<KnowledgeBrowser />} />
        <Route path="/article/:id" element={<ArticleDetail />} />
      </Routes>
    </Router>
  );
}

function HomePage() {
  const navigate = useNavigate();
  const [categories, setCategories] = useState([]);
  const [subCategories, setSubCategories] = useState({}); // 存储每个一级分类的二级分类
  const [activePrimaryTab, setActivePrimaryTab] = useState(null);
  const [activeSecondaryTab, setActiveSecondaryTab] = useState(null);
  const [articles, setArticles] = useState({ list: [], total: 0, pageNum: 1, pageSize: 10, totalPage: 0 });
  const [searchText, setSearchText] = useState('');
  const [showSecondaryMenu, setShowSecondaryMenu] = useState(false);
  const [loading, setLoading] = useState(true);
  const [loadingSubCategories, setLoadingSubCategories] = useState(false);
  const [loadingArticles, setLoadingArticles] = useState(false);
  const [error, setError] = useState(null);

  // 加载二级分类和文章的函数
  const loadSubCategoriesAndArticles = async (category) => {
    if (!category) return;
    
    setLoadingSubCategories(true);
    try {
      // 加载二级分类
      const subCats = await CategoryService.fetchSubCategories(category.id);
      setSubCategories(prev => ({
        ...prev,
        [category.id]: subCats
      }));
      
      // 如果有二级分类，自动选择第一个
      if (subCats.length > 0) {
        const firstSubCat = subCats[0];
        setActiveSecondaryTab(firstSubCat);
        setShowSecondaryMenu(true);
        
        // 加载文章
        setLoadingArticles(true);
        try {
          const articlesData = await CategoryService.fetchArticles(
            category.id,
            firstSubCat.id
          );
          setArticles(articlesData);
        } finally {
          setLoadingArticles(false);
        }
      } else {
        setActiveSecondaryTab(null);
        setShowSecondaryMenu(false);
        setArticles({ list: [], total: 0, pageNum: 1, pageSize: 10, totalPage: 0 });
      }
    } catch (error) {
      console.error('Error loading subcategories:', error);
      setError('加载子分类失败');
    } finally {
      setLoadingSubCategories(false);
    }
  };

  // 初始加载一级分类
  useEffect(() => {
    const loadCategories = async () => {
      try {
        setLoading(true);
        const data = await CategoryService.fetchCategories();
        setCategories(data);
        
        // 如果有分类数据，自动选择第一个一级分类
        if (data.length > 0) {
          const firstCategory = data[0];
          setActivePrimaryTab(firstCategory);
          // 加载二级分类和文章
          await loadSubCategoriesAndArticles(firstCategory);
        }
      } catch (err) {
        setError('加载分类失败，请稍后重试');
        console.error('Error loading categories:', err);
      } finally {
        setLoading(false);
      }
    };

    loadCategories();
  }, []);
  
  // 当一级分类变化时，加载对应的二级分类
  useEffect(() => {
    if (activePrimaryTab) {
      loadSubCategoriesAndArticles(activePrimaryTab);
    }
  }, [activePrimaryTab]);

  const handlePrimaryTabClick = async (category) => {
    setActivePrimaryTab(category);
    setActiveSecondaryTab('');
    
    // 如果已经加载过该分类的二级分类，直接显示
    if (subCategories[category.id]) {
      setShowSecondaryMenu(subCategories[category.id].length > 0);
      return;
    }
    
    // 加载二级分类
    setLoadingSubCategories(true);
    try {
      const subCats = await CategoryService.fetchSubCategories(category.id);
      setSubCategories(prev => ({
        ...prev,
        [category.id]: subCats
      }));
      setShowSecondaryMenu(subCats.length > 0);
      if (subCats.length > 0) {
        setActiveSecondaryTab(subCats[0].name);
      }
    } catch (error) {
      console.error('Error loading subcategories:', error);
      setShowSecondaryMenu(false);
    } finally {
      setLoadingSubCategories(false);
    }
  };

  const handleSecondaryTabClick = async (subCategory) => {
    setActiveSecondaryTab(subCategory);
    setLoadingArticles(true);
    
    try {
      const data = await CategoryService.fetchArticles(
        activePrimaryTab.id,
        subCategory.id
      );
      setArticles(data);
    } catch (error) {
      console.error('Error loading articles:', error);
      setArticles({ list: [], total: 0, pageNum: 1, pageSize: 10, totalPage: 0 });
    } finally {
      setLoadingArticles(false);
    }
  };
  
  // 如果正在加载初始数据，显示全局加载状态
  if (loading) {
    return (
      <div className="app-loading">
        <div className="loading-content">加载中...</div>
      </div>
    );
  }

  // 如果加载出错，显示错误信息
  if (error) {
    return (
      <div className="app-error">
        <div className="error-content">{error}</div>
      </div>
    );
  }

  return (
    <div className="App">
      <header className="app-header">
        <div className="header-title">知识库系统</div>
        
        <nav className="header-tabs">
          {categories.map(category => (
            <div 
              key={category.id}
              className={`tab-item ${activePrimaryTab?.id === category.id ? 'active' : ''}`}
              onClick={() => handlePrimaryTabClick(category)}
            >
              {category.name}
              {loadingSubCategories && activePrimaryTab?.id === category.id && (
                <span className="loading-indicator">...</span>
              )}
            </div>
          ))}
        </nav>
        
        <div className="header-actions">
          <button 
            className="new-knowledge-btn"
            onClick={() => navigate('/new')}
          >
            + 新知识点
          </button>
          <div className="search-box">
            <span className="search-icon">🔍</span>
            <input 
              type="text" 
              placeholder="搜索..." 
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
          </div>
          <div className="avatar">👤</div>
        </div>
      </header>
      
      {showSecondaryMenu && activePrimaryTab && (
        <div className="secondary-menu">
          <div className="secondary-menu-content">
            {loadingSubCategories ? (
              <div className="loading">加载中...</div>
            ) : (
              subCategories[activePrimaryTab.id]?.map((subCategory) => (
                <div 
                  key={subCategory.id}
                  className={`secondary-tab-item ${activeSecondaryTab?.id === subCategory.id ? 'active' : ''}`}
                  onClick={() => handleSecondaryTabClick(subCategory)}
                >
                  {subCategory.name}
                </div>
              ))
            )}
          </div>
        </div>
      )}
      
      <main className="app-content">
        {activeSecondaryTab && activePrimaryTab && (
          <div className="content-area">
            <h2>{activePrimaryTab.name} - {activeSecondaryTab.name}</h2>
            <div className="question-list">
              {loadingArticles ? (
                <div className="loading">加载中...</div>
              ) : articles.list.length > 0 ? (
                articles.list.map((article) => (
                  <div 
                    key={article.id} 
                    className="question-item" 
                    onClick={() => navigate(`/article/${article.id}`)}
                    style={{ cursor: 'pointer' }}
                  >
                    <h3 className="question-title">{article.title}</h3>
                    <div className="question-meta">
                      <span className="meta-item">
                        <span className="meta-label">创建时间：</span>
                        <span className="meta-value">{new Date(article.createdAt).toLocaleDateString()}</span>
                      </span>
                      <span className="meta-item">
                        <span className="meta-label">使用次数：</span>
                        <span className="meta-value">{article.useCount}次</span>
                      </span>
                      <span className="meta-item">
                        <span className="meta-label">浏览次数：</span>
                        <span className="meta-value">{article.viewCount}次</span>
                      </span>
                    </div>
                    <p className="question-summary">{article.summary}</p>
                  </div>
                ))
              ) : (
                <div className="no-data">暂无数据</div>
              )}
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

// Export the App component as default
export default App;
